package com.bp.hearthealth.pulse.lnapps.notification

import android.content.Context
import android.util.Log
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import java.util.concurrent.TimeUnit

class MyFirebaseMessagingService : FirebaseMessagingService() {
    private val WORK_TAG = "my_work"
    // [START receive_message]
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: ${remoteMessage.from}")

        /**
         * 后台配置的参数
         * OpenPage:
         *      0：心率
         *      1：血压
         */
        val mutableMap = remoteMessage.data
        Log.d(TAG, "Message data payload: $mutableMap")
        if (mutableMap.isNotEmpty()) {
            val openPage = remoteMessage.data[Constants.OPEN_PAGE]
            openPage ?: return
            remoteMessage.notification?.let {
                Log.d(TAG, "Message Notification body: ${it.body}")
                Log.d(TAG, "Message Notification imageUrl: ${it.imageUrl}")
                Log.d(TAG, "Message Notification title: ${it.title}")
                Log.d(TAG, "Message Notification icon: ${it.icon}")
                Log.d(TAG, "Message Notification tag: ${it.tag}")
                Log.d(TAG, "Message Notification channelId: ${it.channelId}")
                Log.d(TAG, "Message Notification ticker: ${it.ticker}")
                Log.d(TAG, "Message Notification link: ${it.link}")
                Log.d(TAG, "Message Notification eventTime: ${it.eventTime}")
                if (it.title == null || it.body == null) {
                    return
                }
                NotificationControlManager.notifyCustomNotification(
                    openPage,
                    it.imageUrl!!,
                    it.body!!
                )
            }
            // 检查数据是否需要由长时间运行的作业处理
            if (needsToBeScheduled()) {
                // 对于长时间运行的任务（10 秒或更长时间），请使用 WorkManager。
                startWorkManager()
            } else {
                // 10秒内处理消息
                handleNow()
            }
        }
    }

    private fun needsToBeScheduled() = true

    /**
     * 如果更新 FCM 注册令牌，则调用。 如果以下情况的安全性可能会发生：
     * 之前的令牌已被泄露。 请注意，当FCM 注册令牌最初是生成的，因此您可以在此处检索令牌。
     */
    override fun onNewToken(token: String) {
        Log.d(TAG, "Refreshed token: $token")

        // 如果您想向此应用程序实例发送消息或在服务器端管理此应用程序订阅，发送FCM 向您的应用程序服务器注册令牌。
        sendRegistrationToServer(token)
    }

    private fun startWorkManager() {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        val periodicWorkRequest =
            PeriodicWorkRequest.Builder(MyWorker::class.java, 15, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .build()

        WorkManager.getInstance(applicationContext)
            .enqueueUniquePeriodicWork(
                WORK_TAG,
                ExistingPeriodicWorkPolicy.UPDATE,
                periodicWorkRequest
            )
    }

    private fun handleNow() {
        Log.d(TAG, "Short lived task is done.")
    }

    private fun sendRegistrationToServer(token: String?) {
        // TODO: Implement this method to send token to your app server.
        Log.d(TAG, "sendRegistrationTokenToServer($token)")
    }

    companion object {
        private const val TAG = "MyFirebaseMsgService"
    }

    internal class MyWorker(appContext: Context, workerParams: WorkerParameters) :
        Worker(appContext, workerParams) {
        override fun doWork(): Result {
            LogUtil.i("FirebaseService：doWork")
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                applicationContext.startForegroundService(Intent(BpApplication.context, NotificationService::class.java))
//            } else {
//                applicationContext.startService(Intent(BpApplication.context, NotificationService::class.java))
//            }
            return Result.success()
        }
    }
}